package com.thrc.borrow.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSONObject;
import com.thrc.borrow.entity.Course;
import com.thrc.borrow.entity.Order;
import com.thrc.borrow.pay.util.Log;
import com.thrc.borrow.pay.util.PropertiesUtil;
import com.thrc.borrow.pay.util.SignatureUtils;
import com.thrc.borrow.pay.util.WechatOrderUtils;
import com.thrc.borrow.service.CourseService;
import com.thrc.borrow.vo.CourseVo;

@Controller
@RequestMapping("/wechatPay")
public class WechatPayControler {

	@Autowired
	private CourseService courseService;
	
	/**
	 * 微信公众号调起
	 * 
	 * @param detail
	 *            商品描述
	 * @param desc
	 *            商品详情
	 * @param goodSn
	 *            商品编号
	 * @param openId
	 *            用户openid
	 * @param orderSn
	 *            订单号
	 * @param amount
	 *            金额
	 * @return 返回包装了调起jssdk所需要的函数
	 * @throws Exception
	 */
	@RequestMapping("/jsOrder")
	public String jsOrder(@RequestParam("id")int id, 
			              @RequestParam("openid") String openid,
			              HttpServletResponse resp)throws Exception {
		Course course=new Course();
		course.setId(id);
		CourseVo vo=courseService.selectById(course);
		String out_trade_no=getRandomString(16);
		JSONObject result = WechatOrderUtils.createOrder(vo.getTitle(), "天禾人才在线课程", openid, "192.168.0.1",
				vo.getId()+"", out_trade_no, vo.getPrice_discount()+"", "JSAPI");
		
		//插入购买记录
		Order order=new Order();
		order.setTradeNo(out_trade_no);
		order.setCourseId(id);
		order.setState("apply");
		order.setCreateTime(new Date());
		order.setRemark(openid);
		courseService.insertOrder(order);
		
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().print(result.toString());
		return null;
		
	}

	/**
	 * 生成随机数
	 * @param length
	 * @return
	 */
	public String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();     
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }
	
	/**
	 * 微信支付回调函数
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/callback", method = RequestMethod.POST)
	public void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream is = request.getInputStream();
		HashMap<String, String> map = new HashMap<String, String>();
		Log.info("------------微信回调函数----------------",null);
		// 1、读取传入信息并转换为map
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(is);
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		String payType = "";
		String memberId = "";
		Element root = document.getRootElement();
		List<Element> list = root.elements();
		Log.info("------------获取到元素内容----------------",null);
		for (Element e : list) {
			System.out.println(e.getName());
			System.out.println(e.getText());
			if (e.getName().trim().equals("payType")) {
				payType = e.getText().trim();
			} else if (e.getName().trim().equals("memberId")) {
				memberId = e.getText().trim();
			} else {
				map.put(e.getName().trim(), e.getText().trim());
			}
		}
		is.close();
		// 2、克隆传入的信息并进行验签
		HashMap<String, String> signMap = (HashMap<String, String>) map.clone();
		signMap.remove("sign");
		String key = PropertiesUtil.getValue("wechat.properties", "wx_key");
		String sign = SignatureUtils.signature(signMap, key);
		// System.out.println(sign);
		// System.out.println(map.get("sign"));
		if (!sign.equals(map.get("sign"))) {
			Log.error("微信支付回调函数：验签错误", null);
			return;
		}
		// 信息处理
		String result_code = map.get("result_code");
		try {

			if ("SUCCESS".equals(result_code)) {
				Log.info("回调成功", null);
				// 由于微信后台会同时回调多次，所以需要做防止重复提交操作的判断
				String openid=signMap.get("openid");
				String out_trade_no=signMap.get("out_trade_no");
				
				courseService.buyCourse(openid, out_trade_no);
			} else if ("FAIL".equals(result_code)) {

			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		try {
			// 进行业务逻辑操作

		} catch (Exception e) {
			e.printStackTrace();
			Log.error("回调用户中心错误", e);
		}

		// 返回信息，防止微信重复发送报文
		String result = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
				+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
		PrintWriter out = new PrintWriter(response.getOutputStream());
		out.print(result);
		out.flush();
		out.close();

	}

}
